package com.zzl.springboot_mybatis_demo.controller.web;

import com.gitee.yongzhuzl.commonutil.util.map.MapUtil;
import com.gitee.yongzhuzl.commonutil.util.random.RandomUtil;
import com.zzl.springboot_mybatis_demo.entity.common.JsonResult;
import com.zzl.springboot_mybatis_demo.entity.res.ResultVo;
import com.zzl.springboot_mybatis_demo.entity.user.User;
import com.zzl.springboot_mybatis_demo.util.ResultVoUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Description：与用户相关的RESTful接口
 * Created by 朱正磊 on 2019-09-24 22:57
 */
@RestController
@RequestMapping("/api/web/user")
public class ApiUserController {

    /**
     * description：创建线程安全的Map
     * user 朱正磊
     * time 2019-09-24 23:06
     */
    private static Map<Integer, User> users = Collections.synchronizedMap(new HashMap<>());

    /**
     * description：新增用户信息
     * user 朱正磊
     * time 2019-09-24 23:41
     * @param user 用户详细实体对象
     * @return 返回响应对象信息
     */
    @ApiOperation(value = "新增用户信息", notes = "根据User对象新增用户信息")
    @ApiImplicitParam(name = "user", value = "用户详细实体对象", required = true, dataType = "User")
    @PostMapping("/addUser")
    public ResponseEntity<JsonResult> add(@RequestBody User user) {
        JsonResult jsonResult = new JsonResult();
        try {
            users.put(user.getId(), user);
            jsonResult.setResult(user.getId());
            jsonResult.setStatus("success");
        } catch (Exception e) {
            jsonResult.setResult(e.getClass().getName() + "：" + e.getMessage());
            jsonResult.setStatus("fail");
            e.printStackTrace();
        }
        return ResponseEntity.ok(jsonResult);
    }

    /**
     * description：根据用户ID查询用户
     * user 朱正磊
     * time 2019-09-24 23:25
     * @param id 用户ID
     * @return 返回响应对象信息
     */
    @ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
    @GetMapping("/getUserById/{id}")
    public ResponseEntity<JsonResult> getUserById(@PathVariable Integer id) {
        JsonResult jsonResult = new JsonResult();
        try {
            User user = users.get(id);
            jsonResult.setResult(user);
            jsonResult.setStatus("success");
        } catch (Exception e) {
            jsonResult.setResult(e.getClass().getName() + "：" + e.getMessage());
            jsonResult.setStatus("fail");
            e.printStackTrace();
        }
        return ResponseEntity.ok(jsonResult);
    }

    /**
     * description：查询用户列表
     * user 朱正磊
     * time 2019-09-25 10:40
     * @return 返回响应对象信息
     */
    @ApiOperation(value = "查询用户列表", notes = "查询数据库中用户列表数据")
    @GetMapping("/getUserList")
    public ResponseEntity<JsonResult> getUserList() {
        JsonResult jsonResult = new JsonResult();
        try {
            List<User> userList = new ArrayList<>(users.values());
            jsonResult.setResult(userList);
            jsonResult.setStatus("success");
        } catch (Exception e) {
            jsonResult.setResult(e.getClass().getName() + "：" + e.getMessage());
            jsonResult.setStatus("fail");
            e.printStackTrace();
        }
        return ResponseEntity.ok(jsonResult);
    }

    /**
     * description：根据用户ID删除用户信息
     * user 朱正磊
     * time 2019-09-25 11:14
     * @param id 用户ID
     * @return 返回响应对象信息
     */
    @ApiOperation(value = "删除用户信息", notes = "根据url的id来删除指定的用户信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
    @DeleteMapping("/deleteById/{id}")
    public ResponseEntity<JsonResult> deleteById(@PathVariable Integer id) {
        JsonResult jsonResult = new JsonResult();
        try {
            users.remove(id);
            jsonResult.setResult(id);
            jsonResult.setStatus("success");
        } catch (Exception e) {
            jsonResult.setResult(e.getClass().getName() + "：" + e.getMessage());
            jsonResult.setStatus("fail");
            e.printStackTrace();
        }
        return ResponseEntity.ok(jsonResult);
    }

    /**
     * description：根据用户ID修改用户信息
     * user 朱正磊
     * time 2019-09-25 11:15
     * @param id 用户ID
     * @param user 用户实体对象
     * @return 返回响应对象信息
     */
    @ApiOperation(value = "修改用户信息", notes = "根据url的id来更新指定的用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path"),
            @ApiImplicitParam(name = "user", value = "用户实体对象", required = true, dataType = "User")
    })
    @PutMapping("/editById/{id}")
    public ResponseEntity<JsonResult> editById(@PathVariable Integer id, @RequestBody User user) {
        JsonResult jsonResult = new JsonResult();
        try {
            User data = users.get(id);
            data.setUsername(user.getUsername());
            data.setPassword(user.getPassword());
            data.setAge(user.getAge());
            data.setRealname(user.getRealname());
            data.setCreateTime(user.getCreateTime());
            users.put(id, data);
            jsonResult.setResult(data);
            jsonResult.setStatus("success");
        } catch (Exception e) {
            jsonResult.setResult(e.getClass().getName() + "：" + e.getMessage());
            jsonResult.setStatus("fail");
            e.printStackTrace();
        }
        return ResponseEntity.ok(jsonResult);
    }

    /**
     * description：该方法的目的仅仅是用于演示@ApiIgnore的作用，忽略指定的api接口，不生成api接口文档
     * user 朱正磊
     * time 2019-09-24 23:46
     * @return 返回响应信息
     */
    @ApiIgnore
    @RequestMapping(value = "/jsonTest", method = RequestMethod.POST)
    public String jsonTest() {
        return "hello swagger2";
    }

    /**
     * 注意：paramType = "form" 表示 'Content-Type: application/x-www-form-urlencoded'---Parameter Type 为 formData
     *      paramType = "query" 表示 'Content-Type: application/json' ---Parameter Type 为 query
     *      paramType不指定默认body，表示每个参数都是 'Content-Type: application/json' ---Parameter Type 为 body
     * description: 获取用户信息
     * @author 朱正磊
     * @date 2019-10-13 22:29:41
     * @param request HTTP请求对象
     * @return 返回用户信息
     */
    @ApiOperation(value = "获取用户信息", notes = "根据小程序客户端请求的参数获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "登录名", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "password", value = "登录密码", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "realname", value = "真实姓名", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "String", paramType = "form")
    })
    @PostMapping("/getUser")
    public ResultVo getUser(HttpServletRequest request) {
        try {
            Map<String, String> paramsMap = MapUtil.getParamsMapValueStr(request);
            User user = new User();
            user.setId(Integer.valueOf(RandomUtil.randomNum(6)));
            user.setUsername(paramsMap.get("username"));
            user.setPassword(paramsMap.get("password"));
            user.setRealname(paramsMap.get("realname"));
            user.setCreateTime(new Date());
            user.setAge(Integer.valueOf(paramsMap.get("age")));
            return ResultVoUtil.success(user);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return ResultVoUtil.fail(500, "调用服务接口异常！");
        }
    }

}
